#include <sstream>
#include <iomanip>
#include "../include/ThreadPoolMetrics.h"


// 构造函数
ThreadPoolMetrics::ThreadPoolMetrics()
    :startTime(std::chrono::steady_clock::now())
{}

// 更新队列大小并记录峰值
void ThreadPoolMetrics::updateQueueSize(size_t size)
{
    size_t currentPeek = peakQueueSize.load();
    while(size > currentPeek && peakQueueSize.compare_exchange_weak(currentPeek, size))
    {}
}

// 更新活跃线程数并记录峰值
void ThreadPoolMetrics::updateActiveThreads(size_t count)
{
    this->activeThreads.store(count);
    size_t currentPeak = peakQueueSize.load();
    while(count > currentPeak && peakQueueSize.compare_exchange_weak(currentPeak, count))
    {}
}

// 添加任务执行时间
void ThreadPoolMetrics::addTaskTime(uint64_t timeNs)
{
    totalTaskTimeNs.fetch_add(timeNs);
}

// 获取平均任务执行时间(毫秒)
double ThreadPoolMetrics::getAverageTaskTime() const
{
    size_t compeleted = completedTasks.load();
    if(compeleted == 0)
    {
        return 0.0;
    }

    return static_cast<double>(totalTaskTimeNs.load())/compeleted/1000000.0;
}

// 获取线程池运行时间(秒)
double ThreadPoolMetrics::getUptime() const
{
    auto now = std::chrono::steady_clock::now();
    return std::chrono::duration<double> (now-startTime).count();
}

// 获取任务吞吐量(每秒任务数)
double ThreadPoolMetrics::getThroughput() const
{
    double uptime = this->getUptime();
    if(uptime < 0.0)
    {
        return 0.0;
    }
    return static_cast<double>(this->completedTasks.load() / uptime);
}

// 获取性能报告
std::string ThreadPoolMetrics::getReport() const
{
    std::stringstream ss;
    ss << " 线程池性能报告: " << std::endl;
    ss << " 运行时间: " << getUptime() << " 秒" << std::endl;
    ss << " 总任务数: " << totalTasks.load() << std::endl;
    ss << " 已完成任务数: " << completedTasks.load() << std::endl;
    ss << " 失败任务数: " << failedTasks.load() << std::endl;
    ss << " 当前活跃线程数: " << activeThreads.load() << std::endl;
    ss << " 峰值活跃线程数: " << peakThreads.load() << std::endl;
    ss << " 峰值队列大小: " << peakQueueSize.load() << std::endl;
    ss << " 平均任务执行时间" << getAverageTaskTime() << " 毫秒" << std::endl;
    ss << " 任务吞吐量: " << getThroughput() << " 任务/秒" << std::endl;

    return ss.str();
}